package com.encrypt;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangyan
 * @version $ Id: RsaDemo.java, v 0.1 2022/1/14 10:41 zhangyan Exp $
 */
public class RsaDemo {
    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";

    public static void main(String[] args) throws Exception {
        RSAPublicKey key = getPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnrFFre8PqpPK1VIj64127FYeEmcAo12bhAvHKuWgdKofX5l2Zw+LS+/U5ws/7NfTfcQ3CPAtwbSik3FvmPX0CPWBVKFATNEmGhr43SDuZJz6vS3iE5/vUiVoEouxwuYcXZkt6ktXmEfdBqlZN9dnToUSh8rB4DE9TrTjoj82wenXQqAZ9tk4EGRa95JoHnxctBClSOD+CspdpV2/RscDBQnzNluRURZxxS+EtkNkDSpDwOxH/fel3Xzas1zewQO7G04ZX/+TugVfSz/PUfg2bAOEkpij0PBBG3HrZqn1Hxp4IomXvmLv7FuroRiO2KfP5fwniif5cJgV09nmE99X3wIDAQAB");
        RSAPrivateKey privateKey = getPrivateKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCesUWt7w+qk8rVUiPrjXbsVh4SZwCjXZuEC8cq5aB0qh9fmXZnD4tL79TnCz/s19N9xDcI8C3BtKKTcW+Y9fQI9YFUoUBM0SYaGvjdIO5knPq9LeITn+9SJWgSi7HC5hxdmS3qS1eYR90GqVk312dOhRKHysHgMT1OtOOiPzbB6ddCoBn22TgQZFr3kmgefFy0EKVI4P4Kyl2lXb9GxwMFCfM2W5FRFnHFL4S2Q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TehAOm4oeSqh2eN9DfG19aYSF1N8fMwxefPB07VyVcYjFLchsAzrfy3Ijzqc0mMe2+pGB6fuvAipS0Wn0FkNHIYb+1wiaxXGtBSXRAoGBAPmwQQRG3gA9tmCOLHtW0S+qyz9sm7uNex6adI8RSalPZhuviIrh4V8SiW4n3vj/SJxKw3CLogwVlmeafGWZ5l9fq1rF08JjLWSSfzkxPtTXC2hECo1I+z0uByphCyY6Yh+H+Se3jUjX92I3zRUf58rjrlIcay1ZhdoU/Dk5YFED");
        Map<String, String> dataMap = new HashMap<>(16);
        dataMap.put("1", "2");
        String s = privateEncrypt(JSONObject.toJSONString(dataMap), privateKey);
        System.out.println(s);
        //解密
        System.out.println(publicDecrypt(s, key));
    }

    public static Map<String, String> generateKeys(int keySize) throws Exception {
        //1为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        //2初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //3生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //4得到公钥
        Key publicKey = keyPair.getPublic();
        //4.1公钥base64转码
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        //5得到私钥
        Key privateKey = keyPair.getPrivate();
        //5.1私钥base64转码
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, String> keyPairMap = new HashMap<>(16);
        //6 返回
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 得到公钥
     *
     * @param publicKey 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        return (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
    }

    /**
     * 得到私钥
     *
     * @param privateKey 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] bytes = cipher.doFinal(data.getBytes());
            return Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] bytes1 = Base64.decodeBase64(data);
            byte[] bytes = cipher.doFinal(bytes1);
            return new String(bytes);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥加密
     *
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] bytes = cipher.doFinal(data.getBytes());
            return Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 公钥解密
     *
     * @param data
     * @param publicKey
     * @return
     */

    public static String publicDecrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] bytes = Base64.decodeBase64(data);
            byte[] bytes1 = cipher.doFinal(bytes);
            return new String(bytes1);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

}
